//
//  FinishViewController.m
//  图片故事
//
//  Created by 爽 on 16/3/3.
//  Copyright © 2016年 helloApp. All rights reserved.
//

#import "FinishViewController.h"
#import "Header.h"
#import "LoginViewController.h"
#import <BmobSDK/Bmob.h>
#import <BmobSDK/BmobProFile.h>
#import "MBProgressHUD+PKX.h"
#import "UIImage+Resize.h"
#import "UserInfoModal.h"
#import "LocaData.h"
@interface FinishViewController () <UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,strong)UITextField *TextField;
@property (nonatomic,strong)UITextField *PasswordTextField;
@property (nonatomic,strong)UIButton *Button;
@property (nonatomic, strong) UIImageView *titleImg;
@property (nonatomic, strong) UIAlertController *alertImagePicker;
@property (nonatomic, strong) UIImagePickerController *imagePicker;
@property (nonatomic, copy) NSData *data;
@property (nonatomic, copy)__block NSString *urlStr;
@property (nonatomic,strong) UIImage *image;
@property (nonatomic,strong) NSArray       *headArray;
@end

@implementation FinishViewController

#pragma mark --懒加载
- (NSArray *)headArray {

    if (!_headArray) {
        
        _headArray = [[NSArray alloc] initWithObjects:@"head_01",@"head_02",@"head_03",@"head_04", nil];
    }
    
    return _headArray;
}

- (UIImagePickerController *) imagePicker {
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        [_imagePicker setDelegate:self];
    }
    return _imagePicker;
}

- (UIAlertController *)alertImagePicker {
    if (!_alertImagePicker) {
        _alertImagePicker = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择添加头像的方式" preferredStyle:UIAlertControllerStyleActionSheet ];
        UIAlertAction *camerAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self.imagePicker presentViewController:_imagePicker animated:YES completion:nil];
            } else {
                [MBProgressHUD showError:@"你的设备没有摄像头"];
            }
        }];
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
                self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [self presentViewController:_imagePicker animated:YES completion:nil];
            } else {
                [MBProgressHUD showError:@"您没有获取相册的权限"];
            }
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [_alertImagePicker addAction:camerAction];
        [_alertImagePicker addAction:photoAction];
        [_alertImagePicker addAction:cancelAction];
    }
    return _alertImagePicker;
}

- (UIImageView *)titleImg {
    if (!_titleImg) {
        _titleImg = [[UIImageView alloc] init];
        _titleImg.center = CGPointMake(SCREEN_W / 2, My_Height(130));
        
        _titleImg.bounds = CGRectMake(0, 0, My_Width(80), My_Width(80));
        
        [_titleImg setImage:[UIImage imageNamed:@"hourly"]];
        
        _titleImg.layer.cornerRadius = My_Width(40);
        
        [_titleImg setUserInteractionEnabled:YES];
        [_titleImg.layer setMasksToBounds:YES];
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(action_chanceImage)];
        
        [_titleImg addGestureRecognizer:tapGesture];

    }
    return _titleImg;
}

//完成注册
-(UIButton *)Button {
    if (!_Button) {
        _Button = [UIButton buttonWithType:UIButtonTypeSystem];
        _Button.frame = CGRectMake(My_Width(20), My_Height(331), SCREEN_W - My_Width(50), My_Height(50));
        [_Button setTitle:@"完成注册" forState:UIControlStateNormal];
        _Button.backgroundColor = [UIColor colorWithRed:102 / 255.0 green:214 / 255.0 blue:228 / 255.0 alpha:1];
        _Button.titleLabel.font = [UIFont systemFontOfSize:16.0];
        [_Button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _Button.layer.cornerRadius = My_Height(5);
         [_Button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _Button;
}
//注册密码
-(UITextField *)TextField {
    if (!_TextField) {
        _TextField = [[UITextField alloc] initWithFrame:CGRectMake(My_Width(0), My_Height(200), SCREEN_W, My_Height(50))];
        _TextField.placeholder = @"密码";
        _TextField.font =[UIFont systemFontOfSize:16.0];
        _TextField.backgroundColor = Btn_Color;
        [_TextField setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];
        _TextField.clearButtonMode = UITextFieldViewModeWhileEditing;//右边清楚按钮模式
        _TextField.textAlignment = NSTextAlignmentCenter;
        _TextField.secureTextEntry = YES;
        [_TextField setTextColor:[UIColor grayColor]];
        _TextField.tag = 102;
    }
    return _TextField;
}

//再次确认密码
-(UITextField *)PasswordTextField {
    if (!_PasswordTextField) {
        _PasswordTextField = [[UITextField alloc] initWithFrame:CGRectMake(My_Width(0), My_Height(251), SCREEN_W, My_Height(50))];
        _PasswordTextField.placeholder= @"确认密码";
        _PasswordTextField.font = [UIFont systemFontOfSize:16.0];
        _PasswordTextField.backgroundColor = Btn_Color;
        [_PasswordTextField setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];
        _PasswordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _PasswordTextField.textAlignment = NSTextAlignmentCenter;
        _PasswordTextField.secureTextEntry = YES;
        [_PasswordTextField setTextColor:[UIColor grayColor]];
        _PasswordTextField.tag = 103;
    }
    return _PasswordTextField;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    _data = [NSData data];
    
    [self.view setBackgroundColor:Bg_Color];
   
    [self initNavigation];
}
- (void)initNavigation {
    self.title = @"完成注册";

    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(returnbutton)];
    self.navigationItem.leftBarButtonItem = backItem;
    [self.view addSubview:self.TextField];
    [self.view addSubview:self.PasswordTextField];
    [self.view addSubview:self.Button];
    [self.view addSubview:self.titleImg];
    
}

- (void)action_chanceImage {
    [self presentViewController:self.alertImagePicker animated:YES completion:nil];
}

- (void)buttonAction:(UIButton *)button {
    
    [MBProgressHUD showMessage:@"拼命上传中..."];

    NSString *str = @"^[0-9a-zA-Z]{6,16}";
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
    BOOL isMatch = [pred1 evaluateWithObject:self.TextField.text];
    
    if (UIImagePNGRepresentation(_image) != nil) {
        
        _data = UIImagePNGRepresentation(_image);
    }else if(UIImageJPEGRepresentation(_image, 1) != nil){
        
        _data = UIImageJPEGRepresentation(_image, 1);
    }else {
        
        int x = arc4random() % 4;
    
        _data = UIImagePNGRepresentation([UIImage imageNamed:[self.headArray objectAtIndex:x]]);
    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [BmobProFile uploadFileWithFilename:@"titleImage.jpg" fileData:_data block:^(BOOL isSuccessful, NSError *error, NSString *filename, NSString *url, BmobFile *file) {
            if (isSuccessful){
                [BmobProFile getFileAcessUrlWithFileName:filename callBack:^(BmobFile *file, NSError *error) {
                    if (error) {
                        [MBProgressHUD showError:@"上传头像失败"];
                    } else {
                        _urlStr = file.url;
                        
                        if (self.TextField.text.length == 0 || self.PasswordTextField.text.length == 0) {
                            
                            [MBProgressHUD showError:@"密码不能为空"];
                            
                        } else if (self.TextField.text.length < 6 || self.PasswordTextField.text.length < 6) {
                            
                            [MBProgressHUD showError:@"密码不能小于6位"];
                            
                        } else if (isMatch) {
                            
                            if ([self.TextField.text isEqualToString:self.PasswordTextField.text]) {
                                
                                
                                
                                BmobObject *userBmob = [BmobObject objectWithClassName:@"user"];
                                
                                NSDictionary *dict = @{@"userName":_phoneNum,@"userPassword":self.PasswordTextField.text,@"titleImage":_urlStr};
                                
                                [userBmob saveAllWithDictionary:dict];
                                
                                [userBmob saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                                    
                                    if (isSuccessful) {
                                        
                                        [MBProgressHUD hideHUD];
                                        
                                        UserInfoModal *userInfo = [[UserInfoModal alloc] init];
                                        
                                        [userInfo setUserHead:_urlStr];
                                        [userInfo setUserId:nil];
                                        [userInfo setUserName:_phoneNum];
                                        [userInfo setUserPwd:self.PasswordTextField.text];
                                        
                                        [LocaData saveUserInfo:userInfo];
                                        
                                        [self.navigationController popToRootViewControllerAnimated:YES];
                                        
                                    } else {
                                        
                                        NSLog(@"%@",[error localizedDescription]);
                                        
                                    }
                                    
                                }];
                                
                            } else {
                                
                                [MBProgressHUD showError:@"两次密码输入不一致"];
                            }
                        } else {
                            
                            [MBProgressHUD showError:@"密码格式错误"];
                        }
                    }
                }];
            }
            
        } progress:^(CGFloat progress) {
            
            NSLog(@"%f",progress);
            
        }];
    });
}

- (void)returnbutton {
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -- UIImagePickerController 代理

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    _image = [image resizedImageToFitInSize:CGSizeMake(My_Width(200), My_Height(200)) scaleIfSmaller:YES];
    
    self.titleImg.image = image;

    [self dismissViewControllerAnimated:YES completion:nil];

}




@end
